<?php
include_once("../../includes/config.inc.php");
check_login();
$suserSession=get_suser();
$customer_id=$suserSession['id'];
$model=D('member_group');

//数据保存
if($_REQUEST['a']=='add'){
	if(method_is('post')){
		$data=$_POST;
        $data['str']['group_name']=trim($data['str']['group_name']);
        $data['num']['customer_id']=$customer_id;
        //请求接口
        $configModel=new Model_CustomerConfig();
        $token=$configModel->getToken($customer_id);
        if($data['num']['id']){//修改时
            $retRes=$configModel->editUserGroups($token,$data['num']['group_id'],$data['str']['group_name']);
        }else{
            $retRes=$configModel->createUserGroups($token,$data['str']['group_name']);
            $data['num']['group_id']=$retRes['id'];
        }
        
        if($retRes){
            $res=$model->add($data);
            die('suc');
        }else{
            die('err');
        }
	}else{
		$id=(int)$_GET['id'];
		if($id){
			$smarty->assign('vo',$model->find($id));
		}
		$smarty->setTpl('member/templates/group_add.html')->display();die();
	}
}

//数据删除
if($_REQUEST['a']=='del'){
    //请求接口
    $configModel=new Model_CustomerConfig();
    $token=$configModel->getToken($customer_id);
    $retRes=$configModel->delUserGroups($token,(int)$_POST['group_id']);
    if($retRes){
        $res=$model->del((int)$_POST['id']);
        die('suc');
    }else{
        die('err');
    }
}

//同步分组
if($_REQUEST['a']=='sync'){
    //请求接口
    $configModel=new Model_CustomerConfig();
    $groups=$configModel->getGroups($customer_id);

    if($groups){
        $model->query("delete from member_group where customer_id='{$customer_id}'");
        foreach($groups as $k=>$v){
            $model->insert(array('customer_id'=>$customer_id,'group_id'=>$v['id'],'group_name'=>$v['name'],'group_num'=>$v['count']));
        }
        die('suc');
    }else{
        die('err');
    }
}

//数据列表
$filter['where'] = "customer_id='{$customer_id}'";
$filter['order'] = "group_id asc";
$data = $model->paginate($filter,'*',common_pg('p'),10);
$listArr = $data['data'];
$memberModel=D('member');
foreach($listArr as $k=>$v){
    $row=$memberModel->field("count(id) as count_num")->where("customer_id='{$customer_id}' and group_id='".$v['group_id']."'")->dataRow();
    $listArr[$k]['count_num']=$row['count_num'];
}
$smarty->assign('list',$listArr);
$smarty->assign('page',$model->pager($data['pager']));
$smarty->setTpl('member/templates/group_index.html')->display();